package com.example.onlinemusic.controller;

import com.example.onlinemusic.mapper.LoveMusicMapper;
import com.example.onlinemusic.mapper.MusicMapper;
import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.tooks.Constant;
import com.example.onlinemusic.tooks.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/music")
public class MusicController {
    @Value("${music.local.path}")
    private String SAVE_PATH;
    @Autowired
    private MusicMapper musicMapper;
    @Autowired
    private LoveMusicMapper loveMusicMapper;

    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer,
                                                    @RequestParam("filename") MultipartFile filename,
                                                    HttpServletRequest request) {
        // 1. 进行服务器上传
        String fileNameAndType = filename.getOriginalFilename(); // xxx.mp3
        System.out.println("fileNameAndType: " + fileNameAndType);
        // 2. 查询数据库当中, 是否有当前音乐 [歌曲名 + 歌手]
        // 确定后缀名的位置
        int index = fileNameAndType.lastIndexOf(".");
        // 截取歌名
        String title = fileNameAndType.substring(0,index);
        // 在数据库进行查询
        Music music = musicMapper.findMusicByNameAndSinger(title, singer);
        if (music != null) {
            return new ResponseBodyMessage<>(-1, "已经拥有当前歌曲! ", false);
        }
        String path = SAVE_PATH + fileNameAndType;
        File dest = new File(path);
        if (!dest.exists()) {
            dest.mkdir();
        }
        try {
            filename.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1, "服务器上传失败! ", false);
        }

        // 3. 进行数据库的上传
        //   1) 准备数据
        //   2) 调用 insert
        // 获取用户连接信息
        HttpSession httpSession = request.getSession(false);
        User user = (User) httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userid = user.getId();
        // 播放音乐-> http 请求
        String url = "/music/get?path=" + title;
        // 获取当前时间
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sf.format(new Date());

        try {
            int ret = 0;
            ret = musicMapper.insert(title, singer, time, url, userid);
            if (ret == 1) {
                return new ResponseBodyMessage<>(0, "音乐上传成功! ", true);
            } else {
                return new ResponseBodyMessage<>(-1, "音乐上传数据库失败! ", false);
            }
        } catch (BindingException e) {
            dest.delete();
            return new ResponseBodyMessage<>(-1, "音乐上传数据库失败! ", false);
        }
    }

    // 播放音乐: /music/get?path=xxx.mp3
    @RequestMapping("/get")
    public ResponseEntity<byte[]> func(String path) {
        File file = new File(SAVE_PATH + path);
        byte[] a = null;
        try {
            a = Files.readAllBytes(file.toPath());
            if (a == null) {
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusic(@RequestParam String id, HttpServletRequest request) {
        // 1. 查看要删除的音乐是否存在
        int musicId = Integer.parseInt(id);
        Music music = musicMapper.findMusicById(musicId);
        if (music == null) {
            System.out.println("没有要删除的歌曲! ");
            return new ResponseBodyMessage<>(-1, "没有找到要删除的歌曲! ", false);
        } else {
            // 1) 在数据库中删除音乐
            int ret = musicMapper.deleteMusicById(musicId);
            if (ret == 1) {
                // 2) 在服务器上删除音乐
                String fileName = music.getTitle();
                File file = new File(SAVE_PATH + fileName + ".mp3");
                System.out.println("当前的路径: " + file.getPath());
                if (file.delete()) {
                    // 3) 同步删除 lovemusic 表当中的这个音乐
                    loveMusicMapper.deleteLoveMusicByMusicId(musicId);
                    return new ResponseBodyMessage<>(0, "删除音乐成功! ", true);
                } else {
                    return new ResponseBodyMessage<>(-1, "服务器当中删除音乐失败! ", false);
                }
            } else {
                System.out.println("数据库当中删除音乐失败! ");
                return new ResponseBodyMessage<>(-1, "数据库当中的音乐删除失败! ", false);
            }
        }
    }

    // 批量删除音乐
    @RequestMapping("/deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("ids[]")List<Integer> ids, HttpServletRequest request) {
        System.out.println("所有的ID: " + ids);
        int sum = 0;
        for (int i = 0; i < ids.size(); i++) {
            int musicId = ids.get(i);
            Music music = musicMapper.findMusicById(musicId);
            if (music == null) {
                System.out.println("没有这个 id 的音乐");
                continue;
            }
            int ret = musicMapper.deleteMusicById(musicId);
            if (ret == 1) {
                String fileName = music.getTitle();
                File file = new File(SAVE_PATH + fileName + ".mp3");
                System.out.println("当前的路径: " + file.getPath());
                if (file.delete()) {
                    // 同步删除 lovemusic 表当中的这个音乐
                    loveMusicMapper.deleteLoveMusicByMusicId(musicId);
                    sum += ret;
                }
            }
        }
        if (sum == ids.size()) {
            System.out.println("整体删除成功!! ");
            return new ResponseBodyMessage<>(0, "音乐全部删除成功! ", true);
        }
        return new ResponseBodyMessage<>(-1, "音乐部分删除失败! ", false);
    }

    @RequestMapping("/findmusic")
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required = false) String musicName) {
        List<Music> musicList = null;
        System.out.println("要查询的音乐名: " + musicName);
        if (musicName == null) {
            musicList = musicMapper.findMusic();
        } else {
            musicList = musicMapper.findMusicByName(musicName);
        }
        return new ResponseBodyMessage<>(0, "查询到了所有的音乐", musicList);
    }

}
